<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

class Category extends ActiveRecord{

    public static function tableName(){
        return "{{%category}}";
    }

    public function attributeLabels(){
        return [
            'parentid' => '上级分类',
            'title' => '分类名称',
        ];
    }

    /*
     * 验证规则
     */
    public function rules(){
        return [
          ['parentid','required','message'=>'上级分类不能为空'],
          ['title','required','message'=>'标题名称不能为空'],
          ['createtime','safe'],
        ];
    }

    /*
     * 添加分类
     */
    public function add($data){
        $data['Category']['createtime'] = time();
        if ($this->load($data) && $this->save()) {
            return true;
        }
        return false;
    }


    /*
     * 获取所有分类
     * @return    array
     */
    public function getData()
    {
        $cates = self::find()->asArray()->all();
        return $cates;
    }

    /*
     * 归纳所有分类,每个顶级分来下面显示该分类的子类
     * @param   $cates   array   分类数组
     * @param   $pid     int     父类id
     * @return  array
     */
    public function getTree($cates, $pid = 0)
    {
        $tree = [];
        foreach($cates as $cate){
            if($cate['parentid'] == $pid){
                $tree[] = $cate;
                $tree = array_merge($tree, $this->getTree($cates , $cate['cateid']));
            }
        }

        return $tree;
    }


    /*
     * 为每个分类设置前缀，顶级分类+1个前缀，二级分类+2个前缀，以此类推
     * @param   $data   array    分类数组
     * @param   $p      string   前缀
     * @return  array
     */
    public function setPrefix($data,$p= "|----")
    {
        $tree = [];
        $num = 1;
        $prefix = [0=>1];
        while($val = current($data)){
            $key = key($data);
            if($key > 0){
                if($data[$key-1]['parentid'] != $val['parentid']){
                    $num++;
                }
            }

            if(array_key_exists($val['parentid'],$prefix)){
                $num = $prefix[$val['parentid']];
            }
            $val['title'] = str_repeat($p,$num).$val['title'];
            $prefix[$val['parentid']] = $num;
            $tree[] = $val;
            next($data);
        }
        return $tree ;
    }

    /*
     * 设置下来列表对应数据，分类id对应分类title
     * @return   array
     */
    public function getOptions()
    {
        $data = $this->getData();
        $tree = $this->getTree($data);
        $tree = $this->setPrefix($tree);
        $options = ['添加顶级分类'];

        foreach($tree as $cate) {
            $options[$cate['cateid']] = $cate['title'];
        }
        return $options;
    }


    /*
     * 获取分类列表数据
     * @return    array
     */
    public function getTreeList()
    {
        $data = $this->getData();
        $tree = $this->getTree($data);
        $tree = $this->setPrefix($tree);

        return $tree;
    }

}